package com.data.web.config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Configuration
public class NettyServer {

    @Autowired
    private NettyServerHandler nettyServerHandler;

    private final int PORT = 8084; // TCP 服务端监听的端口
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    @PostConstruct
    public void start() throws InterruptedException {
        // 创建两个线程组
        bossGroup = new NioEventLoopGroup(); // 用于处理客户端连接
        workerGroup = new NioEventLoopGroup(); // 用于处理网络读写

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // 使用 NIO 传输通道
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置连接队列大小
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 保持长连接
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            // 添加自定义的处理器
                            ch.pipeline().
                                    addLast(nettyServerHandler);
                        }
                    });

            // 绑定端口并启动服务
            ChannelFuture future = bootstrap.bind(PORT).sync();
            System.out.println("Netty TCP Server started on port " + PORT);

            // 等待服务端监听端口关闭
            future.channel().closeFuture().sync();
        } finally {
            stop();
        }
    }

    @PreDestroy
    public void stop() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        System.out.println("Netty TCP Server stopped.");
    }
}
